package com.waypolice.manager.service.impl;

import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.common.utils.ReflectionObjectUtil;
import com.waypolice.manager.service.UpmsFileNumService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.mapper.*;
import com.waypolice.mapper.handwriting.CmsJudItemMapperSon;
import com.waypolice.pojo.*;
import io.swagger.models.auth.In;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.*;

/**
 * @Description 卷件管理ServiceImpl
 * @Author wangrang
 * @Date Created in 14:40 2019/3/12
 * @Modified By:
 */
@Service
public class VolAndItemServiceImpl implements VolAndItemService {

    @Autowired
    private CmsJudVolumeMapper cmsJudVolumeMapper;

    @Autowired
    private CmsJudItemMapper cmsJudItemMapper;

    @Autowired
    private UpmsFileNumService upmsFileNumService;

    @Autowired
    private UpmsDictionaryMapper upmsDictionaryMapper;

    @Autowired
    private CmsSinItemMapper cmsSinItemMapper;

    @Override
    public List<CmsJudVolume> selectAll() {
        CmsJudVolumeExample cmsJudVolumeExample = new CmsJudVolumeExample();
        CmsJudVolumeExample.Criteria criteria = cmsJudVolumeExample.createCriteria();
        criteria.andVolArchiveStatusEqualTo(0); //初始只查询新著录的
        cmsJudVolumeExample.setOrderByClause("\"VOL_CREATE_DATE\" DESC");

        List<CmsJudVolume> cmsJudVolumes = cmsJudVolumeMapper.selectByExample(cmsJudVolumeExample);

        return cmsJudVolumes;
    }

    @Override
    public List<CmsJudVolume> selectAllByQueryParms(CmsJudVolumeExample cmsJudVolumeExample) {
        return cmsJudVolumeMapper.selectByExample(cmsJudVolumeExample);
    }

    @Override
    public CmsJudVolume selectCmsJudVolumeByVolId(Long volId) {
        return cmsJudVolumeMapper.selectByPrimaryKey(volId);
    }

    @Override
    public List<CmsJudItem> selectAllByVolId(Long volId,Integer flag) {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        if(flag == 0){
            cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");
        }else if(flag == 2){
            cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");
        } else{
            cmsJudItemExample.setOrderByClause("\"ITEM_NUM\" ASC");
        }
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(volId);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        return cmsJudItems;
    }

    @Override
    public int deleteVolume(Long volId) {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(volId);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        if(cmsJudItems.size()==0){
            int i = cmsJudVolumeMapper.deleteByPrimaryKey(volId);
            return i;
        }else {
            return 2;
        }
    }

    @Override
    public int deleteVolumeAndAllItem(Long volId) throws Exception {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(volId);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        if(cmsJudItems.size()==0){
            int i = cmsJudVolumeMapper.deleteByPrimaryKey(volId);
            return i;
        }else {
            int gal=0;
            for (CmsJudItem cmsJudItem : cmsJudItems) {
                if(StringUtils.isNotBlank(cmsJudItem.getItemStr2()) && "1".equals(cmsJudItem.getItemStr3())){
                    FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                    fastDFSClient.deleteFile(cmsJudItem.getItemStr2());
                }
                int i = cmsJudItemMapper.deleteByPrimaryKey(cmsJudItem.getItemId());
                if(i==0){
                    gal+=1;
                }
            }
            if(gal==0){
                int i = cmsJudVolumeMapper.deleteByPrimaryKey(volId);
                return 1;
            }else {
                return 0;
            }
        }
    }

    @Override
    public int deleteAllItemAndYuanWen(Long volId) throws Exception {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(volId);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        int gal=0;
        for (CmsJudItem cmsJudItem : cmsJudItems) {
            if(StringUtils.isNotBlank(cmsJudItem.getItemStr2()) && "1".equals(cmsJudItem.getItemStr3())){
                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                fastDFSClient.deleteFile(cmsJudItem.getItemStr2());
            }
            int i = cmsJudItemMapper.deleteByPrimaryKey(cmsJudItem.getItemId());
            if(i==0){
                gal+=1;
            }
        }
        if(gal==0){
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public int updateByPrimaryKeySelectiveNoCheck(CmsJudVolume cmsJudVolume) {
        return cmsJudVolumeMapper.updateByPrimaryKeySelective(cmsJudVolume);
    }

    @Override
    public CmsJudItem selectByItemId(Long itemId) {
        return cmsJudItemMapper.selectByPrimaryKey(itemId);
    }

    @Override
    public String selectByPojo(Long itemId) {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItemIdEqualTo(itemId);
        criteria.andItemStr3EqualTo("1");
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        String itemStr2 = cmsJudItems.get(0).getItemStr2();
        if(StringUtils.isNotBlank(itemStr2)) {
            return itemStr2;
        }else {
            return null;
        }
    }

    /**
     * @author:zyp
     * @description 根据主键修改件的内容
     * @date: 2019/3/14 16:52
     * @return 
     */
    @Override
    public void updateItemByPrimaryKeySelective(CmsJudItem cmsJudItem) {
        cmsJudItemMapper.updateByPrimaryKeySelective(cmsJudItem);
    }

    @Override
    public String getFileNumber(CmsJudVolume cmsJudVolume) throws Exception {
        //获取档号规则
        UpmsFileNumExample fileNumExample = new UpmsFileNumExample();
        fileNumExample.setOrderByClause("SORT_NUM asc");
        fileNumExample.or().andStr1EqualTo("1").andPkCodeEqualTo("tradition");
        List<UpmsFileNum> fileNumsLis = upmsFileNumService.selectByExample(fileNumExample);
        StringBuffer strFileNum = new StringBuffer();
        for (int i = 0; i < fileNumsLis.size(); i++) {
            if("fixedValue".equals(fileNumsLis.get(i).getCode())){
                UpmsDictionaryExample upmsDictionaryExample = new UpmsDictionaryExample();
                UpmsDictionaryExample.Criteria criteria = upmsDictionaryExample.createCriteria();
                criteria.andCodeEqualTo("fixedValue");
                List<UpmsDictionary> upmsDictionaries = upmsDictionaryMapper.selectByExample(upmsDictionaryExample);
                String remarks = upmsDictionaries.get(0).getRemarks();
                strFileNum.append(remarks);
            }else {
                String getMethod = ReflectionObjectUtil.getGetMethod(cmsJudVolume, fileNumsLis.get(i).getCode()) == null ? null : ReflectionObjectUtil.getGetMethod(cmsJudVolume, fileNumsLis.get(i).getCode()).toString();
                //String getMethod = ReflectionObjectUtil.getGetMethod(cmsJudVolume, fileNumsLis.get(i).getCode()).toString();

                if(StringUtils.isBlank(getMethod)){
                    return "error";
                }else {
                    strFileNum.append(getMethod);
                }
            }
            if(i != fileNumsLis.size()-1){
                strFileNum.append(fileNumsLis.get(i).getSeparator());
            }

        }
        return strFileNum.toString();
    }

    /**
     * @author:zyp
     * @description
     * @date: 2019/3/21 17:41
     * @return
     */
    @Override
    public JSONArray getItemForMyBorrow(String parentid, Long fileShape) {
        JSONArray jsonArray = null;
        //如果类型是卷 则parentid为单一
        if(fileShape== BorrowConstant.BORROW_FILE_VOLUM){
            CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
            CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
            criteria.andItmeVolIdEqualTo(MathUtils.string2long(parentid));
            List<CmsJudItem> itemlists = cmsJudItemMapper.selectByExample(cmsJudItemExample);
            jsonArray = JSONArray.fromObject(itemlists);
        }else if(fileShape==BorrowConstant.BORROW_FILE_ITEM){
            String[] itemIds = parentid.split(",");
            List<Long> fileId = new ArrayList<>();
            for(String itemId : itemIds){
                fileId.add(MathUtils.string2long(itemId));
            }
            CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
            CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
            criteria.andItemIdIn(fileId);
            List<CmsJudItem> itemlists = cmsJudItemMapper.selectByExample(cmsJudItemExample);
            jsonArray = JSONArray.fromObject(itemlists);
        }else if(fileShape==BorrowConstant.BORROW_FILE_SIN_ITEM){
            String[] itemIds = parentid.split(",");
            List<Long> fileId = new ArrayList<>();
            for(String itemId : itemIds){
                fileId.add(MathUtils.string2long(itemId));
            }
            CmsSinItemExample cmsSinItemExample = new CmsSinItemExample();
            CmsSinItemExample.Criteria criteria = cmsSinItemExample.createCriteria();
            criteria.andItemIdIn(fileId);
            List<CmsSinItem> cmsSinItems = cmsSinItemMapper.selectByExample(cmsSinItemExample);
            jsonArray = JSONArray.fromObject(cmsSinItems);
        }
        return jsonArray;
    }

    /**
     * @author:zyp
     * @description 通过id数组 修改件的状态
     * @date: 2019/3/25 15:20
     * @return 
     */
    @Override
    public void updateItemStatusByIds(long itemStatus, String[] ids) {
        CmsJudItem cmsJudItem = new CmsJudItem();
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        List<Long> longList = new ArrayList<>();
        for (String id : ids){
            longList.add(MathUtils.string2long(id));
        }
        criteria.andItemIdIn(longList);
        cmsJudItem.setItemStatus(itemStatus);
        cmsJudItemMapper.updateByExampleSelective(cmsJudItem,cmsJudItemExample);
    }

    /**
     * @author:zyp
     * @description 根据卷id，将旗下的件修改件状态
     * @date: 2019/4/23 17:16
     * @return
     */
    @Override
    public void updateItemStatusByVoId(long itemStatus, Long voId) {
        CmsJudItem cmsJudItem = new CmsJudItem();
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(voId);
        cmsJudItem.setItemStatus(itemStatus);
        cmsJudItemMapper.updateByExampleSelective(cmsJudItem,cmsJudItemExample);
    }

    /**
     * @author:zyp
     * @description 根据卷的id获取件的数据
     * @date: 2019/4/4 14:24
     * @return 
     */
    @Override
    public List<CmsJudItem> selectAllByVolIds(List<String> ids) {
        List<Long> longIds = new ArrayList<>();
        for(String id : ids ){
            longIds.add(MathUtils.string2long(id));
        }
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdIn(longIds);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        return cmsJudItems;
    }

    /**
     * @author:zyp
     * @description 根据卷id 查看当前卷中是否存在其他状态的文件
     * @date: 2019/6/6 10:20
     * @return
     */
    @Override
    public int isOtherStatusByVoldId(long voId) {
        CmsJudItemExample cmsJudItemExample = new CmsJudItemExample();
        CmsJudItemExample.Criteria criteria = cmsJudItemExample.createCriteria();
        criteria.andItmeVolIdEqualTo(voId);
        criteria.andItemStatusNotEqualTo(0L);
        List<CmsJudItem> cmsJudItems = cmsJudItemMapper.selectByExample(cmsJudItemExample);
        return cmsJudItems.size();
    }


    /**
     * @author:zyp
     * @description 根据id获取 当前卷 或 件 的具体 载体类型 （有实体 无实体  共存）
     * @date: 2019/3/19 9:12
     * @return
     */
    @Override
    public String getCarrierType(String type, String id) {
        String carrierType = "";
        //如果当前的是卷
        if(BorrowConstant.BORROW_FILE_VOLUM == MathUtils.string2int(type)){
            carrierType = cmsJudVolumeMapper.selectByPrimaryKey(MathUtils.string2long(id)).getVolCarrier();
        }else if(BorrowConstant.BORROW_FILE_ITEM == MathUtils.string2int(type)){
            CmsJudItem cmsJudItem = cmsJudItemMapper.selectByPrimaryKey(MathUtils.string2long(id));
            carrierType = cmsJudVolumeMapper.selectByPrimaryKey(cmsJudItem.getItmeVolId()).getVolCarrier();
        }else if(BorrowConstant.BORROW_FILE_SIN_ITEM == MathUtils.string2int(type)){
            carrierType = cmsSinItemMapper.selectByPrimaryKey(MathUtils.string2long(id)).getItemCarrier();
        }
        return carrierType;
    }
}
